<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>前端开发工作计划表</title>
    <style>
        body {
            font-family: "Microsoft YaHei", Arial, sans-serif;
            line-height: 1.6;
            margin: 40px;
            color: #333;
        }
        
        h1 {
            text-align: center;
            color: #2c3e50;
            margin-bottom: 30px;
            font-size: 24px;
        }
        
        h2 {
            color: #34495e;
            border-bottom: 2px solid #3498db;
            padding-bottom: 5px;
            margin-top: 30px;
            font-size: 18px;
        }
        
        h3 {
            color: #2980b9;
            margin-top: 25px;
            font-size: 16px;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
            font-size: 12px;
        }
        
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
            vertical-align: top;
            position: relative;
        }
        
        th {
            background-color: #f8f9fa;
            font-weight: bold;
            text-align: center;
        }
        
        /* 可编辑单元格样式 */
        .editable {
            cursor: pointer;
            transition: background-color 0.2s;
        }
        
        .editable:hover {
            background-color: #f0f8ff !important;
        }
        
        .editing {
            background-color: #e3f2fd !important;
            padding: 0 !important;
        }
        
        .footer .editing {
            background-color: #e3f2fd !important;
            padding: 0 !important;
            line-height: inherit;
            vertical-align: baseline;
        }
        
        .footer .editable {
            display: inline;
            vertical-align: baseline;
        }
        
        .edit-input {
            width: 100%;
            height: 100%;
            border: none;
            background: transparent;
            font-family: inherit;
            font-size: inherit;
            padding: 8px;
            outline: none;
            resize: none;
            min-height: 20px;
        }
        
        .status-pending { color: #f39c12; }
        .status-progress { color: #3498db; }
        .status-completed { color: #27ae60; }
        .status-delayed { color: #e74c3c; }
        .status-cancelled { color: #95a5a6; }
        
        .summary-row {
            background-color: #ecf0f1;
            font-weight: bold;
        }
        
        .risk-high { background-color: #fee; }
        .risk-medium { background-color: #fff3cd; }
        .risk-low { background-color: #d4edda; }
        
        .page-break {
            page-break-before: always;
        }
        
        .notes {
            background-color: #f8f9fa;
            padding: 15px;
            border-left: 4px solid #3498db;
            margin: 20px 0;
        }
        
        .footer {
            margin-top: 40px;
            padding-top: 20px;
            border-top: 1px solid #ddd;
            font-size: 11px;
            color: #666;
        }
        
        /* 控制按钮样式 */
        .controls {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1000;
            background: white;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            border: 1px solid #ddd;
        }
        
        .btn {
            background: #3498db;
            color: white;
            border: none;
            padding: 8px 16px;
            margin: 5px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            display: block;
            width: 100%;
        }
        
        .btn:hover {
            background: #2980b9;
        }
        
        .btn-success {
            background: #27ae60;
        }
        
        .btn-success:hover {
            background: #219a52;
        }
        
        .btn-primary {
            background: #007bff;
        }
        
        .btn-primary:hover {
            background: #0056b3;
        }
        
        .edit-hint {
            color: #666;
            font-size: 11px;
            margin-bottom: 10px;
            text-align: center;
        }
        
        /* 状态下拉选择框样式 */
        .status-select {
            width: 100%;
            border: none;
            background: transparent;
            font-family: inherit;
            font-size: inherit;
            padding: 4px;
            outline: none;
            cursor: pointer;
        }
        
        .status-select option {
            background: white;
            color: #333;
        }
        
        /* 日期选择器样式 */
        .date-picker {
            width: 100%;
            border: none;
            background: transparent;
            font-family: inherit;
            font-size: inherit;
            padding: 4px;
            outline: none;
            cursor: pointer;
        }
        
        /* 确保datetime-local控件正常显示 */
        input[type="datetime-local"] {
            width: 100% !important;
            min-width: 180px;
            box-sizing: border-box;
        }
        
        /* 最后更新时间显示样式（非可编辑） */
        .datetime-display {
            color: inherit;
            display: inline;
            vertical-align: baseline;
        }
        
        /* footer中编辑输入框的特殊样式 */
        .footer .edit-input {
            width: auto;
            min-width: 120px;
            max-width: 200px;
            display: inline-block;
            padding: 0;
            margin: 0;
            border: none;
            background: transparent;
            font-family: inherit;
            font-size: inherit;
            line-height: inherit;
            vertical-align: baseline;
            height: auto;
            min-height: 0;
            box-sizing: border-box;
        }
        
        /* 表格下方按钮样式 */
        .table-btn {
            white-space: nowrap;
            background: #3498db;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            margin: 5px;
        }
        
        .table-btn:hover {
            background: #2980b9;
        }
        
        .btn-container {
            text-align: center;
            margin: 15px 0;
        }
        
        @media print {
            body { margin: 20px; }
            .page-break { page-break-before: always; }
            
            /* 隐藏控制面板和按钮 */
            .controls { display: none !important; }
            .btn-container { display: none !important; }
            button { display: none !important; }
            .table-btn { display: none !important; }
            
            /* 隐藏编辑提示 */
            .edit-hint { display: none !important; }
            
            /* 移除编辑相关样式 */
            .editable:hover { background-color: transparent !important; }
            .editable { cursor: default !important; }
            
            /* 隐藏使用说明部分 */
            .notes h3:contains("使用说明"),
            .notes h3:contains("推荐工作流程") { 
                display: none !important; 
            }
            .notes:has(h3:contains("使用说明")),
            .notes:has(h3:contains("推荐工作流程")) { 
                display: none !important; 
            }
            
            /* 如果浏览器不支持:has()，使用JavaScript隐藏 */
            .notes.usage-notes { display: none !important; }
            
            /* 隐藏操作列 - 只对任务表格生效 */
            #pageTaskTable th:last-child,
            #pageTaskTable td:last-child,
            #techTaskTable th:last-child,
            #techTaskTable td:last-child {
                display: none !important;
            }
            
            /* 确保表格宽度适应 */
            table {
                width: 100% !important;
                table-layout: auto !important;
            }
            
            /* 优化打印布局 */
            h1 { font-size: 18pt; }
            h2 { font-size: 14pt; }
            h3 { font-size: 12pt; }
            table { font-size: 10pt; }
            th, td { padding: 6px; }
        }
    </style>
</head>
<body>
    <!-- 控制面板 -->
    <div class="controls">
        <div class="edit-hint">双击单元格编辑<br>数字列:限制正数+自动单位<br>状态/优先级:下拉选择<br>日期列:日期选择器<br>自动保存+缓存<br>支持导入导出项目数据</div>
        <button class="btn btn-success" onclick="generateWordDocument()">生成Word文档</button>
        <button class="btn btn-primary" onclick="generateHTMLDocument()">生成HTML文档</button>
        <button class="btn" onclick="exportProjectData()">导出项目数据</button>
        <button class="btn" onclick="importProjectData()">导入项目数据</button>
        <button class="btn" onclick="resetAllData()">重置数据</button>
        <button class="btn" onclick="printDocument()">打印文档</button>
        
        <!-- 隐藏的文件输入框，用于导入 -->
        <input type="file" id="importFileInput" accept=".json" style="display: none;" onchange="handleFileImport(event)">
    </div>

    <h1>前端开发工作计划表</h1>
    
    <h2>项目基本信息</h2>
    <table>
        <tr>
            <th style="width: 15%;">项目名称</th>
            <th style="width: 25%;">计划周期</th>
            <th style="width: 15%;">负责人</th>
            <th style="width: 15%;">项目优先级</th>
            <th style="width: 30%;">项目描述</th>
        </tr>
        <tr>
            <td class="editable">[填写项目名称]</td>
            <td class="editable date-range-cell">[开始日期] ~ [结束日期]</td>
            <td class="editable">[您的姓名]</td>
            <td class="editable priority-cell">[高/中/低]</td>
            <td class="editable">[填写项目简要描述]</td>
        </tr>
    </table>
    
    <h2>开发任务计划</h2>
    
    <h3>页面开发任务</h3>
    <table id="pageTaskTable">
        <tr>
            <th style="width: 5%;">序号</th>
            <th style="width: 15%;">页面/模块名称</th>
            <th style="width: 20%;">功能描述</th>
            <th style="width: 20%;">开发内容</th>
            <th style="width: 8%;">预估工时(天)</th>
            <th style="width: 10%;">开始时间</th>
            <th style="width: 10%;">结束时间</th>
            <th style="width: 8%;">状态</th>
            <th style="width: 4%;">操作</th>
        </tr>
        <tr>
            <td>1</td>
            <td class="editable">登录页面</td>
            <td class="editable">用户登录认证</td>
            <td class="editable">登录表单、验证逻辑、密码找回</td>
            <td class="editable">2天</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable status-cell status-pending">未开始</td>
            <td class="editable"></td>
        </tr>
        <tr>
            <td>2</td>
            <td class="editable">首页/仪表板</td>
            <td class="editable">数据概览展示</td>
            <td class="editable">数据图表、卡片组件、导航菜单</td>
            <td class="editable">4天</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable status-cell status-pending">未开始</td>
            <td class="editable"></td>
        </tr>
        <tr>
            <td>3</td>
            <td class="editable">用户管理模块</td>
            <td class="editable">用户CRUD操作</td>
            <td class="editable">用户列表、新增/编辑弹窗、权限设置</td>
            <td class="editable">5天</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable status-cell status-pending">未开始</td>
            <td class="editable"></td>
        </tr>
        <tr>
            <td>4</td>
            <td class="editable">商品管理模块</td>
            <td class="editable">商品信息管理</td>
            <td class="editable">商品列表、商品详情、库存管理</td>
            <td class="editable">6天</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable status-cell status-pending">未开始</td>
            <td class="editable"></td>
        </tr>
        <tr>
            <td>5</td>
            <td class="editable">订单管理模块</td>
            <td class="editable">订单处理流程</td>
            <td class="editable">订单列表、订单详情、状态更新</td>
            <td class="editable">5天</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable status-cell status-pending">未开始</td>
            <td class="editable"></td>
        </tr>
        <tr>
            <td>6</td>
            <td class="editable">系统设置页面</td>
            <td class="editable">系统配置管理</td>
            <td class="editable">参数配置、权限设置、日志查看</td>
            <td class="editable">3天</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable status-cell status-pending">未开始</td>
            <td class="editable"></td>
        </tr>
        <tr>
            <td>7</td>
            <td class="editable">报表统计模块</td>
            <td class="editable">数据分析展示</td>
            <td class="editable">图表组件、数据筛选、导出功能</td>
            <td class="editable">4天</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable status-cell status-pending">未开始</td>
            <td class="editable"></td>
        </tr>
        <tr>
            <td>8</td>
            <td class="editable">个人中心页面</td>
            <td class="editable">用户个人信息</td>
            <td class="editable">信息编辑、密码修改、操作记录</td>
            <td class="editable">2天</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable status-cell status-pending">未开始</td>
            <td class="editable"></td>
        </tr>
        <tr class="summary-row">
            <td colspan="4"><strong>页面开发小计</strong></td>
            <td><strong>31天</strong></td>
            <td colspan="4"></td>
        </tr>
    </table>
    
    <div class="btn-container">
        <button class="table-btn" onclick="addPageRow()">➕ 新增页面任务</button>
    </div>
    
    <h3>技术实现任务</h3>
    <table id="techTaskTable">
        <tr>
            <th style="width: 5%;">序号</th>
            <th style="width: 20%;">技术任务</th>
            <th style="width: 30%;">具体内容</th>
            <th style="width: 10%;">预估工时(天)</th>
            <th style="width: 12%;">开始时间</th>
            <th style="width: 12%;">结束时间</th>
            <th style="width: 8%;">状态</th>
            <th style="width: 3%;">操作</th>
        </tr>
        <tr>
            <td>1</td>
            <td class="editable">项目初始化</td>
            <td class="editable">脚手架搭建、依赖安装、基础配置</td>
            <td class="editable">1天</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable status-cell status-pending">未开始</td>
            <td class="editable"></td>
        </tr>
        <tr>
            <td>2</td>
            <td class="editable">路由配置</td>
            <td class="editable">页面路由、权限路由、懒加载</td>
            <td class="editable">1天</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable status-cell status-pending">未开始</td>
            <td class="editable"></td>
        </tr>
        <tr>
            <td>3</td>
            <td class="editable">状态管理</td>
            <td class="editable">Vuex/Pinia配置、数据流设计</td>
            <td class="editable">2天</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable status-cell status-pending">未开始</td>
            <td class="editable"></td>
        </tr>
        <tr>
            <td>4</td>
            <td class="editable">通用组件库</td>
            <td class="editable">公共组件封装、样式规范</td>
            <td class="editable">3天</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable status-cell status-pending">未开始</td>
            <td class="editable"></td>
        </tr>
        <tr>
            <td>5</td>
            <td class="editable">API接口对接</td>
            <td class="editable">接口封装、错误处理、数据模拟</td>
            <td class="editable">2天</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable status-cell status-pending">未开始</td>
            <td class="editable"></td>
        </tr>
        <tr>
            <td>6</td>
            <td class="editable">权限系统</td>
            <td class="editable">登录拦截、角色权限、菜单控制</td>
            <td class="editable">3天</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable status-cell status-pending">未开始</td>
            <td class="editable"></td>
        </tr>
        <tr>
            <td>7</td>
            <td class="editable">响应式适配</td>
            <td class="editable">移动端适配、多终端兼容</td>
            <td class="editable">2天</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable status-cell status-pending">未开始</td>
            <td class="editable"></td>
        </tr>
        <tr>
            <td>8</td>
            <td class="editable">性能优化</td>
            <td class="editable">代码分割、懒加载、缓存策略</td>
            <td class="editable">2天</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable status-cell status-pending">未开始</td>
            <td class="editable"></td>
        </tr>
        <tr class="summary-row">
            <td colspan="3"><strong>技术实现小计</strong></td>
            <td><strong>16天</strong></td>
            <td colspan="4"></td>
        </tr>
    </table>
    
    <div class="btn-container">
        <button class="table-btn" onclick="addTechRow()">➕ 新增技术任务</button>
    </div>
    
    <div class="page-break"></div>
    
    <h2>工时汇总</h2>
    <table>
        <tr>
            <th style="width: 20%;">类别</th>
            <th style="width: 20%;">总预估工时(天)</th>
            <th style="width: 20%;">实际工时(天)</th>
            <th style="width: 20%;">差异</th>
            <th style="width: 20%;">完成率</th>
        </tr>
        <tr>
            <td class="editable">页面开发</td>
            <td class="editable">31天</td>
            <td class="editable actual-hours-cell">[填写]</td>
            <td class="editable">[填写]</td>
            <td class="editable completion-rate-cell">[%]</td>
        </tr>
        <tr>
            <td class="editable">技术实现</td>
            <td class="editable">16天</td>
            <td class="editable actual-hours-cell">[填写]</td>
            <td class="editable">[填写]</td>
            <td class="editable completion-rate-cell">[%]</td>
        </tr>
        <tr class="summary-row">
            <td><strong>项目总计</strong></td>
            <td><strong>47天</strong></td>
            <td><strong>[填写]</strong></td>
            <td><strong>[填写]</strong></td>
            <td class="editable completion-rate-cell"><strong>[%]</strong></td>
        </tr>
    </table>
    
    <h2>里程碑节点</h2>
    <table>
        <tr>
            <th style="width: 25%;">里程碑</th>
            <th style="width: 20%;">计划完成时间</th>
            <th style="width: 20%;">实际完成时间</th>
            <th style="width: 25%;">交付内容</th>
            <th style="width: 10%;">状态</th>
        </tr>
        <tr>
            <td class="editable">项目搭建完成</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable">基础框架、开发环境</td>
            <td class="editable status-cell status-pending">未开始</td>
        </tr>
        <tr>
            <td class="editable">核心页面完成</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable">主要业务页面</td>
            <td class="editable status-cell status-pending">未开始</td>
        </tr>
        <tr>
            <td class="editable">功能集成完成</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable">全部功能模块</td>
            <td class="editable status-cell status-pending">未开始</td>
        </tr>
        <tr>
            <td class="editable">项目上线</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable date-cell">[日期]</td>
            <td class="editable">生产环境部署</td>
            <td class="editable status-cell status-pending">未开始</td>
        </tr>
    </table>
    
    <h2>风险评估</h2>
    <table>
        <tr>
            <th style="width: 25%;">风险项</th>
            <th style="width: 10%;">风险等级</th>
            <th style="width: 30%;">影响</th>
            <th style="width: 35%;">应对措施</th>
        </tr>
        <tr class="risk-medium">
            <td class="editable">API接口延期</td>
            <td class="editable risk-level-cell">中</td>
            <td class="editable">影响页面数据对接进度</td>
            <td class="editable">提前准备mock数据，并行开发</td>
        </tr>
        <tr class="risk-medium">
            <td class="editable">产品需求&设计稿变更</td>
            <td class="editable risk-level-cell">中</td>
            <td class="editable">可能导致返工</td>
            <td class="editable">前期充分沟通，锁定设计方案</td>
        </tr>
        <tr class="risk-low">
            <td class="editable">第三方组件兼容性</td>
            <td class="editable risk-level-cell">低</td>
            <td class="editable">影响部分功能实现</td>
            <td class="editable">提前调研，准备备选方案</td>
        </tr>
        <tr class="risk-high">
            <td class="editable">人员变动</td>
            <td class="editable risk-level-cell">高</td>
            <td class="editable">严重影响项目进度</td>
            <td class="editable">做好知识共享和文档记录</td>
        </tr>
    </table>
    
    <div class="notes">
        <h3>状态说明</h3>
        <ul>
            <li><span class="status-pending">未开始</span>: 任务尚未开始</li>
            <li><span class="status-progress">进行中</span>: 任务正在进行</li>
            <li><span class="status-completed">已完成</span>: 任务已完成</li>
            <li><span class="status-delayed">已延期</span>: 任务超出预期时间</li>
            <li><span class="status-cancelled">已取消</span>: 任务被取消</li>
        </ul>
    </div>
    
    <div class="notes">
        <h3>使用说明</h3>
        <ol>
            <li><strong>编辑功能</strong>：双击任何蓝色背景的单元格即可进行编辑，数据会自动保存到浏览器缓存</li>
            <li><strong>普通列</strong>：双击后显示文本输入框，回车或点击其他地方保存</li>
            <li><strong>数字列（预估工时、实际工时）</strong>：双击后显示数字输入框，自动添加"天"单位，不允许负数</li>
            <li><strong>完成率列</strong>：双击后显示数字输入框，自动添加"%"符号，限制0-100范围</li>
            <li><strong>状态列</strong>：双击后显示下拉选择框，选择后自动保存并应用对应颜色</li>
            <li><strong>优先级列/风险等级列</strong>：双击后显示下拉选择框（高/中/低），选择后自动保存，风险等级会改变整行颜色</li>
            <li><strong>日期列</strong>：双击后显示日期选择器，选择后自动保存为"xxxx年xx月xx日"格式</li>
            <li><strong>日期范围列</strong>：双击后显示开始和结束两个日期选择器，可用Tab键切换，选择完两个日期后3秒自动保存，或点击✓按钮手动保存</li>
            <li><strong>工时汇总</strong>：实际工时和完成率（包括总计行）可编辑，差异由系统自动计算（|实际工时-预估工时|）</li>
            <li><strong>汇总数据</strong>：页面开发和技术实现的小计会自动计算，工时汇总的总预估工时会自动同步</li>
            <li><strong>添加/删除任务</strong>：使用每个表格下方的"新增任务"按钮可以添加新行，点击"删除"按钮可删除对应行</li>
            <li><strong>文档导出</strong>：生成Word或HTML文档，文件名包含当前时间和负责人姓名，自动移除操作列和使用说明</li>
            <li><strong>数据导出</strong>：点击"导出项目数据"将所有编辑内容保存为JSON文件（格式：项目名称_数据备份_时间戳.json），便于备份和下次导入</li>
            <li><strong>数据导入</strong>：点击"导入项目数据"选择之前导出的JSON文件，可完整恢复所有编辑内容，实现项目数据的持续编辑</li>
            <li><strong>数据缓存</strong>：所有编辑数据会自动保存到浏览器缓存，刷新页面不会丢失当前编辑内容</li>
            <li><strong>工作建议</strong>：建议每日更新任务状态和实际工时，定期导出项目数据备份，系统会自动计算各种汇总数据</li>
        </ol>

        <h3>推荐工作流程</h3>
        <ol>
            <li><strong>首次使用</strong>：编辑工作计划表 → 导出项目数据备份 → 导出Word/HTML文档</li>
            <li><strong>持续编辑</strong>：导入上次的项目数据 → 继续编辑更新 → 导出新的数据备份 → 导出更新后的文档</li>
            <li><strong>团队协作</strong>：可通过共享JSON数据文件在团队成员间传递项目数据</li>
            <li><strong>版本管理</strong>：每次重要节点可导出数据备份，文件名包含时间戳，便于版本追踪</li>
        </ol>
    </div>
    
    <div class="footer">
        <p><strong>创建日期</strong>: <span class="editable date-cell">[填写日期]</span> &nbsp;&nbsp;&nbsp; <strong>最后更新</strong>: <span class="datetime-display">-</span> &nbsp;&nbsp;&nbsp; <strong>文档版本</strong>: <span class="editable">v1.0</span></p>
    </div>

    <!-- FileSaver.js用于文件下载 -->
    <script src="https://cdn.jsdelivr.net/npm/file-saver@2.0.5/dist/FileSaver.min.js"></script>


    <script>
        // 编辑功能实现
        let isEditing = false;
        let currentEditCell = null;

        // 获取当前日期的工具函数
        function getCurrentDateString() {
            const now = new Date();
            const year = now.getFullYear();
            const month = now.getMonth() + 1;
            const day = now.getDate();
            return `${year}年${month}月${day}日`;
        }

        // 获取当前完整时间的工具函数（精确到时分）
        function getCurrentDateTimeString() {
            const now = new Date();
            const year = now.getFullYear();
            const month = now.getMonth() + 1;
            const day = now.getDate();
            const hour = String(now.getHours()).padStart(2, '0');
            const minute = String(now.getMinutes()).padStart(2, '0');
            return `${year}年${month}月${day}日 ${hour}:${minute}`;
        }

        function sanitizeEstimateCell(cell){
            // 只保留数字和小数点，不允许负数
            const num = parseFloat(cell.textContent.replace(/[^0-9.]/g, '')) || 0;
            // 确保不为负数
            const validNum = num < 0 ? 0 : num;
            // 保留一位小数以内
            const fixed = Number.isInteger(validNum) ? validNum : parseFloat(validNum.toFixed(1));
            cell.textContent = fixed + '天';
            return fixed;
        }

        function updateTableSummary(tableId){
            const table=document.getElementById(tableId);
            if(!table) return 0;
            
            let estimateIndex=-1;
            const header=table.rows[0];
            for(let i=0;i<header.cells.length;i++){
                if(header.cells[i].innerText.includes('预估工时')){
                    estimateIndex=i;
                    break;
                }
            }
            if(estimateIndex===-1) return 0;
            
            let sum=0;
            const rows=table.querySelectorAll('tr:not(.summary-row):not(:first-child)');
            rows.forEach((r)=>{
                const cell=r.cells[estimateIndex];
                if(cell){ 
                    sum += sanitizeEstimateCell(cell);
                }
            });
            
            const summaryRow=table.querySelector('tr.summary-row');
            if(summaryRow){
                let summaryCell;
                if (tableId === 'pageTaskTable') {
                    summaryCell = summaryRow.cells[1];
                } else if (tableId === 'techTaskTable') {
                    summaryCell = summaryRow.cells[1];
                }
                
                if(summaryCell) {
                    summaryCell.innerHTML='<strong>'+sum+'天</strong>';
                }
            }
            return sum;
        }

        function updateOverallSummary(){
            const pageSum=updateTableSummary('pageTaskTable');
            const techSum=updateTableSummary('techTaskTable');
            const summaryTableHeading = Array.from(document.querySelectorAll('h2')).find(h=>h.textContent.includes('工时汇总'));
            if(!summaryTableHeading) return;
            const summaryTable = summaryTableHeading.nextElementSibling;
            if(!summaryTable || summaryTable.tagName!=='TABLE') return;
            if(summaryTable.rows.length>=4){
                summaryTable.rows[1].cells[1].textContent=pageSum+'天';
                summaryTable.rows[2].cells[1].textContent=techSum+'天';
                summaryTable.rows[3].cells[1].innerHTML='<strong>'+(pageSum+techSum)+'天</strong>';
                
                // 计算并更新实际工时总计
                updateWorkTimeSummaryTotals(summaryTable);
            }
        }
        
        function updateWorkTimeSummaryTotals(summaryTable) {
            if (!summaryTable || summaryTable.rows.length < 4) return;
            
            // 计算实际工时总计
            let totalActualHours = 0;
            let totalDifference = 0;
            let totalEstimatedHours = 0;
            
            // 遍历页面开发和技术实现两行（第1行和第2行，索引1和2）
            for (let i = 1; i <= 2; i++) {
                const row = summaryTable.rows[i];
                if (!row || row.cells.length < 5) continue;
                
                // 预估工时（第2列）
                const estimatedText = row.cells[1].textContent || '0天';
                const estimated = Math.max(0, parseFloat(estimatedText.replace(/[^0-9.]/g, '')) || 0);
                totalEstimatedHours += estimated;
                
                // 实际工时（第3列）
                const actualText = row.cells[2].textContent || '0天';
                const actual = Math.max(0, parseFloat(actualText.replace(/[^0-9.]/g, '')) || 0);
                totalActualHours += actual;
                
                // 计算差异：|实际工时 - 预估工时|，并更新单行的差异列
                const difference = Math.abs(actual - estimated);
                totalDifference += difference;
                
                // 更新当前行的差异列（第4列）
                if (actual > 0 || estimated > 0) { // 只有当有实际数据时才更新
                    const fixed = Number.isInteger(difference) ? difference : parseFloat(difference.toFixed(1));
                    row.cells[3].textContent = fixed + '天';
                }
            }
            
            // 更新总计行（第3行，索引3）
            const totalRow = summaryTable.rows[3];
            if (totalRow && totalRow.cells.length >= 5) {
                // 只有当实际工时不为0时才显示，否则保持原样
                if (totalActualHours > 0) {
                    totalRow.cells[2].innerHTML = `<strong>${totalActualHours}天</strong>`;
                }
                // 更新差异总计
                const totalDiffFixed = Number.isInteger(totalDifference) ? totalDifference : parseFloat(totalDifference.toFixed(1));
                totalRow.cells[3].innerHTML = `<strong>${totalDiffFixed}天</strong>`;
                
            }
        }

        // 为所有可编辑单元格添加双击事件
        document.addEventListener('DOMContentLoaded', function() {
            // 为现有行补充删除按钮
            ['pageTaskTable','techTaskTable'].forEach(tblId=>{
                const tbl=document.getElementById(tblId);
                if(!tbl) return;
                const rows=tbl.querySelectorAll('tr:not(.summary-row):not(:first-child)');
                // 找到预估工时列
                let estIdx=-1;
                const head=tbl.rows[0];
                for(let i=0;i<head.cells.length;i++){
                    if(head.cells[i].innerText.includes('预估工时')){estIdx=i;break;}
                }
                rows.forEach(row=>{
                    // 删除按钮
                    let last=row.querySelector('td:last-child');
                    if(!last){last=document.createElement('td');row.appendChild(last);} 
                    if(!last.querySelector('button')){
                        last.innerHTML='<button class="table-btn" onclick="deleteRow(this)">删除</button>';
                    }
                    // 预估列格式化 & 监听
                    if(estIdx!==-1){
                       const estCell=row.cells[estIdx];
                       if(estCell){
                          sanitizeEstimateCell(estCell);
                          estCell.addEventListener('blur',()=>{sanitizeEstimateCell(estCell);updateTableSummary(tblId);updateOverallSummary();});
                       }
                    }
                });
                updateTableSummary(tblId);
            });
            // 初始化汇总
            updateOverallSummary();
            
            // 初始化风险等级行样式
            const riskLevelCells = document.querySelectorAll('.risk-level-cell');
            riskLevelCells.forEach(cell => {
                const row = cell.closest('tr');
                const riskLevel = cell.textContent.trim();
                if (row) {
                    // 移除所有风险样式类
                    row.classList.remove('risk-high', 'risk-medium', 'risk-low');
                    
                    // 根据风险等级添加对应样式类
                    switch(riskLevel) {
                        case '高':
                            row.classList.add('risk-high');
                            break;
                        case '中':
                            row.classList.add('risk-medium');
                            break;
                        case '低':
                            row.classList.add('risk-low');
                            break;
                    }
                }
            });
            
            // 初始化底部时间字段
            initializeFooterTimes();
            
            // 从sessionStorage恢复数据
            loadFromSessionStorage();
            
            // 确保最后更新时间有值（如果恢复数据后仍然为空）
            const updateTimeSpan = document.querySelector('.footer .datetime-display');
            if (updateTimeSpan && updateTimeSpan.textContent.trim() === '') {
                updateTimeSpan.textContent = '-';
            }
            // 限制工时汇总表格的可编辑列，仅允许"实际工时""差异""完成率"
            (function(){
                const summaryHeading = Array.from(document.querySelectorAll('h2')).find(h=>h.textContent.includes('工时汇总'));
                if(!summaryHeading) return;
                const summaryTbl = summaryHeading.nextElementSibling;
                if(!summaryTbl || summaryTbl.tagName!=='TABLE') return;
                const headerCells = Array.from(summaryTbl.rows[0].cells);
                
                // 找到各列的索引
                let actualHoursColIndex = -1;
                let completionRateColIndex = -1;
                const editableCols = headerCells.reduce((arr, cell, idx)=>{
                    if(cell.innerText.includes('实际工时')){
                        actualHoursColIndex = idx;
                        arr.push(idx);
                    } else if(cell.innerText.includes('完成率')){
                        completionRateColIndex = idx;
                        arr.push(idx);
                    }
                    return arr;
                },[]);
                
                // 处理每一行
                for(let i=1;i<summaryTbl.rows.length-1;i++){ // 排除表头和总计行
                    const row = summaryTbl.rows[i];
                    for(let j=0;j<row.cells.length;j++){
                        if(!editableCols.includes(j)){
                            row.cells[j].classList.remove('editable');
                        } else {
                            // 为实际工时列添加特殊类
                            if(j === actualHoursColIndex){
                                row.cells[j].classList.add('actual-hours-cell');
                            }
                            // 为完成率列添加特殊类
                            if(j === completionRateColIndex){
                                row.cells[j].classList.add('completion-rate-cell');
                            }
                        }
                    }
                }
                
                // 处理总计行：只保留完成率列可编辑，其他列不可编辑
                const totalRow = summaryTbl.rows[summaryTbl.rows.length-1];
                if(totalRow && totalRow.classList.contains('summary-row')){
                    for(let j=0;j<totalRow.cells.length;j++){
                        if(j === completionRateColIndex){
                            // 完成率列保持可编辑，并添加特殊类
                            totalRow.cells[j].classList.add('editable', 'completion-rate-cell');
                        } else {
                            // 其他列不可编辑
                            totalRow.cells[j].classList.remove('editable');
                        }
                    }
                }
            })();
            const editableCells = document.querySelectorAll('.editable');
            editableCells.forEach(cell => {
                cell.addEventListener('dblclick', function() {
                    if (!isEditing) {
                        startEdit(this);
                    }
                });
            });

            // 点击其他地方保存编辑
            document.addEventListener('click', function(e) {
                if (isEditing && !e.target.closest('.editing')) {
                    saveEdit();
                }
            });
        });

        function startEdit(cell) {
            if (isEditing) return;
            
            isEditing = true;
            currentEditCell = cell;
            
            const originalText = cell.innerHTML;
            const originalBgColor = window.getComputedStyle(cell).backgroundColor;
            
            cell.classList.add('editing');
            
            // 判断是否为状态列
            if (cell.classList.contains('status-cell')) {
                // 创建下拉选择框
                const select = document.createElement('select');
                select.className = 'edit-input status-select';
                
                const options = [
                    { value: '未开始', class: 'status-pending' },
                    { value: '进行中', class: 'status-progress' },
                    { value: '已完成', class: 'status-completed' },
                    { value: '已延期', class: 'status-delayed' },
                    { value: '已取消', class: 'status-cancelled' }
                ];
                
                options.forEach(option => {
                    const opt = document.createElement('option');
                    opt.value = option.value;
                    opt.textContent = option.value;
                    if (option.value === originalText.trim()) {
                        opt.selected = true;
                    }
                    select.appendChild(opt);
                });
                
                cell.innerHTML = '';
                cell.appendChild(select);
                
                select.focus();
                
                // 选择改变时保存
                select.addEventListener('change', function() {
                    saveEdit();
                });
                
                // 失去焦点时保存
                select.addEventListener('blur', function() {
                    setTimeout(() => saveEdit(), 100);
                });
                
                // 按键处理
                select.addEventListener('keydown', function(e) {
                    if (e.key === 'Enter') {
                        e.preventDefault();
                        saveEdit();
                    } else if (e.key === 'Escape') {
                        cancelEdit(originalText);
                    }
                });
            } else if (cell.classList.contains('datetime-cell')) {
                // 创建日期时间选择器容器
                const container = document.createElement('div');
                container.style.display = 'flex';
                container.style.alignItems = 'center';
                container.style.gap = '5px';
                container.style.width = '100%';
                
                // 创建日期输入框
                const dateInput = document.createElement('input');
                dateInput.type = 'date';
                dateInput.className = 'edit-input date-picker';
                dateInput.style.width = '60%';
                
                // 创建时间输入框
                const timeInput = document.createElement('input');
                timeInput.type = 'time';
                timeInput.className = 'edit-input date-picker';
                timeInput.style.width = '35%';
                
                // 解析现有日期时间
                let hasExistingValue = false;
                if (originalText.includes('年') && originalText.includes('月') && originalText.includes('日') && !originalText.includes('[填写日期]')) {
                    const datetimeMatch = originalText.match(/(\d{4})年(\d{1,2})月(\d{1,2})日(?:\s+(\d{1,2}):(\d{1,2})(?::(\d{1,2}))?)?/);
                    if (datetimeMatch) {
                        const year = datetimeMatch[1];
                        const month = datetimeMatch[2].padStart(2, '0');
                        const day = datetimeMatch[3].padStart(2, '0');
                        const hour = datetimeMatch[4] ? datetimeMatch[4].padStart(2, '0') : '00';
                        const minute = datetimeMatch[5] ? datetimeMatch[5].padStart(2, '0') : '00';
                        
                        dateInput.value = `${year}-${month}-${day}`;
                        timeInput.value = `${hour}:${minute}`;
                        hasExistingValue = true;
                    }
                }
                
                // 如果没有现有值，设置为当前时间
                if (!hasExistingValue) {
                    const now = new Date();
                    const year = now.getFullYear();
                    const month = String(now.getMonth() + 1).padStart(2, '0');
                    const day = String(now.getDate()).padStart(2, '0');
                    const hour = String(now.getHours()).padStart(2, '0');
                    const minute = String(now.getMinutes()).padStart(2, '0');
                    
                    dateInput.value = `${year}-${month}-${day}`;
                    timeInput.value = `${hour}:${minute}`;
                }
                
                container.appendChild(dateInput);
                container.appendChild(timeInput);
                
                cell.innerHTML = '';
                cell.appendChild(container);
                
                dateInput.focus();
                
                // 为两个输入框添加事件监听
                [dateInput, timeInput].forEach(input => {
                    input.addEventListener('change', function() {
                        saveEdit();
                    });
                    
                    input.addEventListener('blur', function() {
                        setTimeout(() => {
                            // 检查焦点是否还在容器内
                            if (!container.contains(document.activeElement)) {
                                saveEdit();
                            }
                        }, 100);
                    });
                    
                    input.addEventListener('keydown', function(e) {
                        if (e.key === 'Enter') {
                            e.preventDefault();
                            saveEdit();
                        } else if (e.key === 'Escape') {
                            cancelEdit(originalText);
                        } else if (e.key === 'Tab') {
                            // Tab键在两个输入框之间切换
                            if (input === dateInput && !e.shiftKey) {
                                e.preventDefault();
                                timeInput.focus();
                            } else if (input === timeInput && e.shiftKey) {
                                e.preventDefault();
                                dateInput.focus();
                            }
                        }
                    });
                });
                
                // 阻止容器点击事件冒泡
                container.addEventListener('click', function(e) {
                    e.stopPropagation();
                });
            } else if (cell.classList.contains('date-cell')) {
                // 创建日期选择器
                const input = document.createElement('input');
                input.type = 'date';
                input.className = 'edit-input date-picker';
                
                // 如果已有日期，转换为input格式
                if (originalText.includes('年') && originalText.includes('月') && originalText.includes('日')) {
                    const dateMatch = originalText.match(/(\d{4})年(\d{1,2})月(\d{1,2})日/);
                    if (dateMatch) {
                        const year = dateMatch[1];
                        const month = dateMatch[2].padStart(2, '0');
                        const day = dateMatch[3].padStart(2, '0');
                        input.value = `${year}-${month}-${day}`;
                    }
                }
                
                cell.innerHTML = '';
                cell.appendChild(input);
                
                input.focus();
                
                // 选择改变时保存
                input.addEventListener('change', function() {
                    saveEdit();
                });
                
                // 失去焦点时保存
                input.addEventListener('blur', function() {
                    setTimeout(() => saveEdit(), 100);
                });
                
                // 按键处理
                input.addEventListener('keydown', function(e) {
                    if (e.key === 'Enter') {
                        e.preventDefault();
                        saveEdit();
                    } else if (e.key === 'Escape') {
                        cancelEdit(originalText);
                    }
                });
            } else if (cell.classList.contains('date-range-cell')) {
                // 创建日期范围选择器
                const container = document.createElement('div');
                container.style.display = 'flex';
                container.style.alignItems = 'center';
                container.style.gap = '5px';
                
                const startInput = document.createElement('input');
                startInput.type = 'date';
                startInput.className = 'edit-input date-picker';
                startInput.style.width = '45%';
                
                const separator = document.createElement('span');
                separator.textContent = ' ~ ';
                separator.style.fontSize = '12px';
                
                const endInput = document.createElement('input');
                endInput.type = 'date';
                endInput.className = 'edit-input date-picker';
                endInput.style.width = '45%';
                
                // 解析现有日期范围
                const rangeMatch = originalText.match(/(\d{4})年(\d{1,2})月(\d{1,2})日\s*~\s*(\d{4})年(\d{1,2})月(\d{1,2})日/);
                if (rangeMatch) {
                    const startYear = rangeMatch[1];
                    const startMonth = rangeMatch[2].padStart(2, '0');
                    const startDay = rangeMatch[3].padStart(2, '0');
                    const endYear = rangeMatch[4];
                    const endMonth = rangeMatch[5].padStart(2, '0');
                    const endDay = rangeMatch[6].padStart(2, '0');
                    
                    startInput.value = `${startYear}-${startMonth}-${startDay}`;
                    endInput.value = `${endYear}-${endMonth}-${endDay}`;
                }
                
                container.appendChild(startInput);
                container.appendChild(separator);
                container.appendChild(endInput);
                
                cell.innerHTML = '';
                cell.appendChild(container);
                
                startInput.focus();
                
                // 日期改变时的处理
                let saveTimeout;
                let hasStartDate = false;
                let hasEndDate = false;
                
                function checkAndSave() {
                    // 只有当两个日期都选择了，或者用户明确离开编辑区域时才保存
                    if ((startInput.value && endInput.value) || 
                        (!container.contains(document.activeElement) && document.activeElement !== container)) {
                        if (saveTimeout) {
                            clearTimeout(saveTimeout);
                        }
                        saveEdit();
                    }
                }
                
                [startInput, endInput].forEach(input => {
                    input.addEventListener('change', function() {
                        // 更新状态
                        hasStartDate = !!startInput.value;
                        hasEndDate = !!endInput.value;
                        
                        // 清除之前的延迟保存
                        if (saveTimeout) {
                            clearTimeout(saveTimeout);
                        }
                        
                        // 如果两个日期都选择了，延迟3秒保存（给用户修改的时间）
                        if (hasStartDate && hasEndDate) {
                            saveTimeout = setTimeout(() => {
                                saveEdit();
                            }, 3000);
                        }
                        // 如果只选择了一个日期，不自动保存，等待用户选择第二个
                    });
                    
                    input.addEventListener('blur', function() {
                        // 检查焦点是否移动到另一个日期输入框或容器外
                        setTimeout(() => {
                            const activeElement = document.activeElement;
                            const isInContainer = container.contains(activeElement);
                            
                            // 只有当焦点完全离开容器，且不是在选择日期时才保存
                            if (!isInContainer && 
                                activeElement !== startInput && 
                                activeElement !== endInput &&
                                !activeElement.classList.contains('date-picker')) {
                                
                                if (saveTimeout) {
                                    clearTimeout(saveTimeout);
                                }
                                saveEdit();
                            }
                        }, 200); // 增加延迟时间，确保用户有时间点击第二个输入框
                    });
                    
                    input.addEventListener('focus', function() {
                        // 获得焦点时清除自动保存
                        if (saveTimeout) {
                            clearTimeout(saveTimeout);
                        }
                    });
                    
                    input.addEventListener('keydown', function(e) {
                        if (e.key === 'Enter') {
                            e.preventDefault();
                            if (saveTimeout) {
                                clearTimeout(saveTimeout);
                            }
                            saveEdit();
                        } else if (e.key === 'Escape') {
                            if (saveTimeout) {
                                clearTimeout(saveTimeout);
                            }
                            cancelEdit(originalText);
                        } else if (e.key === 'Tab') {
                            // Tab键在两个输入框之间切换，不立即保存
                            e.preventDefault();
                            if (input === startInput && !endInput.value) {
                                endInput.focus();
                            } else if (input === endInput && !startInput.value) {
                                startInput.focus();
                            } else {
                                // 如果两个都有值，Tab就正常保存
                                if (saveTimeout) {
                                    clearTimeout(saveTimeout);
                                }
                                saveEdit();
                            }
                        }
                    });
                });
                
                // 为容器添加点击事件，阻止冒泡
                container.addEventListener('click', function(e) {
                    e.stopPropagation();
                });
                
                // 添加一个保存按钮，让用户可以手动保存
                const saveBtn = document.createElement('button');
                saveBtn.textContent = '✓';
                saveBtn.style.marginLeft = '5px';
                saveBtn.style.padding = '2px 6px';
                saveBtn.style.fontSize = '12px';
                saveBtn.style.border = '1px solid #ddd';
                saveBtn.style.background = '#f8f9fa';
                saveBtn.style.cursor = 'pointer';
                saveBtn.style.borderRadius = '3px';
                saveBtn.title = '保存日期';
                
                saveBtn.addEventListener('click', function(e) {
                    e.stopPropagation();
                    if (saveTimeout) {
                        clearTimeout(saveTimeout);
                    }
                    saveEdit();
                });
                
                container.appendChild(saveBtn);
            } else if (cell.classList.contains('priority-cell') || cell.classList.contains('risk-level-cell')) {
                // 创建优先级/风险等级下拉选择框
                const select = document.createElement('select');
                select.className = 'edit-input status-select';
                
                const options = ['高', '中', '低'];
                
                options.forEach(option => {
                    const opt = document.createElement('option');
                    opt.value = option;
                    opt.textContent = option;
                    if (originalText.includes(option)) {
                        opt.selected = true;
                    }
                    select.appendChild(opt);
                });
                
                cell.innerHTML = '';
                cell.appendChild(select);
                
                select.focus();
                
                // 选择改变时保存
                select.addEventListener('change', function() {
                    saveEdit();
                });
                
                // 失去焦点时保存
                select.addEventListener('blur', function() {
                    setTimeout(() => saveEdit(), 100);
                });
                
                // 按键处理
                select.addEventListener('keydown', function(e) {
                    if (e.key === 'Enter') {
                        e.preventDefault();
                        saveEdit();
                    } else if (e.key === 'Escape') {
                        cancelEdit(originalText);
                    }
                });
            } else {
                // 判断是否为数字输入列
                const isEstimateColumn = (() => {
                    const tbl = cell.closest('table');
                    if (!tbl) return false;
                    const headerCell = tbl.rows[0].cells[cell.cellIndex];
                    return headerCell && headerCell.innerText.includes('预估工时');
                })();
                
                const isActualHoursColumn = cell.classList.contains('actual-hours-cell');
                const isCompletionRateColumn = cell.classList.contains('completion-rate-cell');

                let input;
                if (isEstimateColumn || isActualHoursColumn || isCompletionRateColumn) {
                    // 数字输入，限制只能填写数字或小数
                    input = document.createElement('input');
                    input.type = 'number';
                    input.step = '0.1';
                    input.min = '0';
                    if (isCompletionRateColumn) {
                        input.max = '100'; // 完成率最大为100%
                    }
                    input.className = 'edit-input';
                    // 让数字输入框填满单元格并取消默认宽度
                    input.style.width = '100%';
                    input.style.boxSizing = 'border-box';
                    const num = parseFloat(originalText.replace(/[^0-9.]/g, ''));
                    input.value = isNaN(num) ? '' : num;
                    
                    // 标记当前单元格的类型
                    if (isEstimateColumn) {
                        cell.dataset.isEstimate = 'true';
                    } else if (isActualHoursColumn) {
                        cell.dataset.isActualHours = 'true';
                    } else if (isCompletionRateColumn) {
                        cell.dataset.isCompletionRate = 'true';
                    }
                } else {
                    // 普通文本输入框 - 对于footer中的短文本使用input，其他使用textarea
                    const isFooterCell = cell.closest('.footer');
                    if (isFooterCell) {
                        input = document.createElement('input');
                        input.type = 'text';
                        input.className = 'edit-input';
                        input.value = originalText.replace(/<[^>]*>/g, ''); // 移除HTML标签
                    } else {
                        input = document.createElement('textarea');
                        input.className = 'edit-input';
                        input.value = originalText.replace(/<[^>]*>/g, ''); // 移除HTML标签
                    }
                    cell.dataset.isEstimate = 'false';
                    cell.dataset.isActualHours = 'false';
                    cell.dataset.isCompletionRate = 'false';
                }

                cell.innerHTML = '';
                cell.appendChild(input);

                input.focus();
                if (input.select) input.select();

                // 回车保存
                input.addEventListener('keydown', function(e) {
                    if (e.key === 'Enter') {
                        e.preventDefault();
                        saveEdit();
                    } else if (e.key === 'Escape') {
                        cancelEdit(originalText);
                    } else if (e.key === '-' || e.key === 'Minus') {
                        // 阻止输入负号
                        e.preventDefault();
                    }
                });
                
                // 添加输入验证，防止粘贴负数
                input.addEventListener('input', function(e) {
                    const value = parseFloat(e.target.value);
                    if (!isNaN(value) && value < 0) {
                        e.target.value = Math.abs(value); // 转为正数
                    }
                });
            }
            
            // 存储原始数据
            cell.dataset.originalText = originalText;
            cell.dataset.originalBgColor = originalBgColor;
        }

        function saveEdit() {
            if (!isEditing || !currentEditCell) return;
            
            const input = currentEditCell.querySelector('.edit-input');
            let newText;
            
            if (currentEditCell.classList.contains('status-cell')) {
                // 状态列处理
                const select = input;
                newText = select.value;
                currentEditCell.innerHTML = newText;
                
                // 移除所有状态类
                currentEditCell.classList.remove('status-pending', 'status-progress', 'status-completed', 'status-delayed', 'status-cancelled');
                
                // 根据选择的值添加对应状态类
                switch(newText) {
                    case '未开始':
                        currentEditCell.classList.add('status-pending');
                        break;
                    case '进行中':
                        currentEditCell.classList.add('status-progress');
                        break;
                    case '已完成':
                        currentEditCell.classList.add('status-completed');
                        break;
                    case '已延期':
                        currentEditCell.classList.add('status-delayed');
                        break;
                    case '已取消':
                        currentEditCell.classList.add('status-cancelled');
                        break;
                }
            } else if (currentEditCell.classList.contains('date-cell')) {
                // 单个日期列处理
                const dateInput = input;
                if (dateInput.value) {
                    const date = new Date(dateInput.value);
                    const year = date.getFullYear();
                    const month = date.getMonth() + 1;
                    const day = date.getDate();
                    newText = `${year}年${month}月${day}日`;
                } else {
                    newText = '[填写日期]';
                }
                currentEditCell.innerHTML = newText;
            } else if (currentEditCell.classList.contains('datetime-cell')) {
                // 日期时间列处理
                const container = currentEditCell.querySelector('div');
                const dateInput = container.querySelector('input[type="date"]');
                const timeInput = container.querySelector('input[type="time"]');
                
                if (dateInput.value && timeInput.value) {
                    // 解析日期
                    const date = new Date(dateInput.value);
                    const year = date.getFullYear();
                    const month = date.getMonth() + 1;
                    const day = date.getDate();
                    
                    // 解析时间
                    const timeParts = timeInput.value.split(':');
                    const hour = timeParts[0];
                    const minute = timeParts[1];
                    
                    newText = `${year}年${month}月${day}日 ${hour}:${minute}`;
                } else if (dateInput.value) {
                    // 只有日期，时间设为00:00
                    const date = new Date(dateInput.value);
                    const year = date.getFullYear();
                    const month = date.getMonth() + 1;
                    const day = date.getDate();
                    newText = `${year}年${month}月${day}日 00:00`;
                } else {
                    newText = '[填写日期]';
                }
                currentEditCell.innerHTML = newText;
            } else if (currentEditCell.classList.contains('date-range-cell')) {
                // 日期范围列处理
                const container = currentEditCell.querySelector('div');
                const startInput = container.querySelectorAll('.date-picker')[0];
                const endInput = container.querySelectorAll('.date-picker')[1];
                
                if (startInput && endInput && startInput.value && endInput.value) {
                    const startDate = new Date(startInput.value);
                    const endDate = new Date(endInput.value);
                    
                    const startYear = startDate.getFullYear();
                    const startMonth = startDate.getMonth() + 1;
                    const startDay = startDate.getDate();
                    
                    const endYear = endDate.getFullYear();
                    const endMonth = endDate.getMonth() + 1;
                    const endDay = endDate.getDate();
                    
                    newText = `${startYear}年${startMonth}月${startDay}日 ~ ${endYear}年${endMonth}月${endDay}日`;
                } else if (startInput && startInput.value) {
                    // 只有开始日期
                    const startDate = new Date(startInput.value);
                    const startYear = startDate.getFullYear();
                    const startMonth = startDate.getMonth() + 1;
                    const startDay = startDate.getDate();
                    newText = `${startYear}年${startMonth}月${startDay}日 ~ [结束日期]`;
                } else if (endInput && endInput.value) {
                    // 只有结束日期
                    const endDate = new Date(endInput.value);
                    const endYear = endDate.getFullYear();
                    const endMonth = endDate.getMonth() + 1;
                    const endDay = endDate.getDate();
                    newText = `[开始日期] ~ ${endYear}年${endMonth}月${endDay}日`;
                } else {
                    newText = '[开始日期] ~ [结束日期]';
                }
                currentEditCell.innerHTML = newText;
            } else if (currentEditCell.classList.contains('priority-cell') || currentEditCell.classList.contains('risk-level-cell')) {
                // 优先级/风险等级列处理
                const select = input;
                newText = select.value;
                currentEditCell.innerHTML = newText;
                
                // 如果是风险等级列，更新整行的风险样式类
                if (currentEditCell.classList.contains('risk-level-cell')) {
                    const row = currentEditCell.closest('tr');
                    if (row) {
                        // 移除所有风险样式类
                        row.classList.remove('risk-high', 'risk-medium', 'risk-low');
                        
                        // 根据选择的风险等级添加对应样式类
                        switch(newText) {
                            case '高':
                                row.classList.add('risk-high');
                                break;
                            case '中':
                                row.classList.add('risk-medium');
                                break;
                            case '低':
                                row.classList.add('risk-low');
                                break;
                        }
                    }
                }
            } else {
                const isEstimate = currentEditCell.dataset.isEstimate === 'true';
                const isActualHours = currentEditCell.dataset.isActualHours === 'true';
                const isCompletionRate = currentEditCell.dataset.isCompletionRate === 'true';
                
                if (isEstimate || isActualHours) {
                    // 预估工时列/实际工时列处理，自动补"天"并限制为数字，不允许负数
                    const num = parseFloat(input.value);
                    const validNum = isNaN(num) || num < 0 ? 0 : num; // 负数或无效值转为0
                    const fixed = Number.isInteger(validNum) ? validNum : parseFloat(validNum.toFixed(1));
                    newText = fixed + '天';
                    currentEditCell.innerHTML = newText;
                } else if (isCompletionRate) {
                    // 完成率列处理，自动补"%"并限制为数字，不允许负数，最大100%
                    const num = parseFloat(input.value);
                    let validNum = isNaN(num) || num < 0 ? 0 : num; // 负数或无效值转为0
                    validNum = validNum > 100 ? 100 : validNum; // 超过100%限制为100%
                    const fixed = Number.isInteger(validNum) ? validNum : parseFloat(validNum.toFixed(1));
                    newText = fixed + '%';
                    currentEditCell.innerHTML = newText;
                } else {
                    // 普通文本列处理
                    newText = input.value.trim();
                    currentEditCell.innerHTML = newText || '[填写]';
                    
                    // 恢复状态样式
                    updateStatusClass(currentEditCell, newText);
                }
            }

            // 更新汇总信息
            const parentTable = currentEditCell.closest('table');
            if(parentTable && (parentTable.id === 'pageTaskTable' || parentTable.id === 'techTaskTable')){
                updateTableSummary(parentTable.id);
                updateOverallSummary();
            } else {
                updateOverallSummary();
            }
            
            currentEditCell.classList.remove('editing');
            
            isEditing = false;
            currentEditCell = null;
            
            // 保存到sessionStorage
            saveToSessionStorage();
        }

        // 保存数据到sessionStorage
        function saveToSessionStorage() {
            try {
                const data = {};
                
                // 分别处理不同的区域
                
                // 1. 项目基本信息（固定结构）
                const projectInfoTable = document.querySelector('h2:first-of-type + table');
                if (projectInfoTable && projectInfoTable.rows.length > 1) {
                    const infoRow = projectInfoTable.rows[1];
                    data['project_name'] = infoRow.cells[0]?.innerHTML || '';
                    data['project_period'] = infoRow.cells[1]?.innerHTML || '';
                    data['project_leader'] = infoRow.cells[2]?.innerHTML || '';
                    data['project_priority'] = infoRow.cells[3]?.innerHTML || '';
                    data['project_desc'] = infoRow.cells[4]?.innerHTML || '';
                }
                
                // 2. 页面开发任务（动态结构，需要保存完整表格数据）
                const pageTable = document.getElementById('pageTaskTable');
                if (pageTable) {
                    const pageData = [];
                    for (let i = 1; i < pageTable.rows.length; i++) { // 跳过表头
                        const row = pageTable.rows[i];
                        if (row.classList.contains('summary-row')) break; // 遇到汇总行停止
                        
                        const rowData = [];
                        for (let j = 0; j < row.cells.length; j++) {
                            rowData.push({
                                content: row.cells[j].innerHTML,
                                className: row.cells[j].className
                            });
                        }
                        pageData.push(rowData);
                    }
                    data['pageTaskData'] = pageData;
                }
                
                // 3. 技术实现任务（动态结构）
                const techTable = document.getElementById('techTaskTable');
                if (techTable) {
                    const techData = [];
                    for (let i = 1; i < techTable.rows.length; i++) { // 跳过表头
                        const row = techTable.rows[i];
                        if (row.classList.contains('summary-row')) break; // 遇到汇总行停止
                        
                        const rowData = [];
                        for (let j = 0; j < row.cells.length; j++) {
                            rowData.push({
                                content: row.cells[j].innerHTML,
                                className: row.cells[j].className
                            });
                        }
                        techData.push(rowData);
                    }
                    data['techTaskData'] = techData;
                }
                
                // 4. 其他固定区域（工时汇总、里程碑、风险评估、footer等）
                const otherEditableCells = document.querySelectorAll('.editable');
                otherEditableCells.forEach((cell, index) => {
                    try {
                        const table = cell.closest('table');
                        if (table && (table.id === 'pageTaskTable' || table.id === 'techTaskTable')) {
                            return; // 跳过已处理的任务表格
                        }
                        
                        let sectionName, rowIndex = 0, cellIndex = 0;
                        
                        // 检查是否是footer区域
                        const footerDiv = cell.closest('.footer');
                        if (footerDiv) {
                            // footer区域特殊处理
                            sectionName = 'footer';
                            const spans = footerDiv.querySelectorAll('.editable');
                            cellIndex = Array.from(spans).indexOf(cell);
                        } else if (table) {
                            // 表格内的单元格
                            const h2Element = table.previousElementSibling;
                            sectionName = h2Element?.textContent?.trim() || 'unknown';
                            const row = cell.closest('tr');
                            
                            if (table.rows && row) {
                                const rowsArray = Array.from(table.rows);
                                rowIndex = rowsArray.indexOf(row);
                                if (rowIndex === -1) rowIndex = 0;
                            }
                            
                            if (row && row.cells && cell) {
                                const cellsArray = Array.from(row.cells);
                                cellIndex = cellsArray.indexOf(cell);
                                if (cellIndex === -1) cellIndex = 0;
                            }
                        } else {
                            // 其他情况使用通用索引
                            sectionName = 'other';
                            cellIndex = index;
                        }
                        
                        const key = `${sectionName}_row${rowIndex}_cell${cellIndex}`;
                        data[key] = {
                            content: cell.innerHTML || '',
                            className: cell.className || ''
                        };
                    } catch (error) {
                        console.warn('保存单元格数据时出错:', error, cell);
                    }
                });
                
                // 特殊保存最后更新时间（非可编辑字段）
                const lastModifiedSpan = document.querySelector('.footer .datetime-display');
                if (lastModifiedSpan) {
                    // 如果最后更新时间是默认值"-"，则设置为当前时间
                    if (lastModifiedSpan.textContent === '-' || lastModifiedSpan.textContent.trim() === '') {
                        lastModifiedSpan.textContent = getCurrentDateTimeString();
                        data['last_modified_time'] = getCurrentDateTimeString();
                    } else {
                        data['last_modified_time'] = lastModifiedSpan.textContent;
                    }
                }
                
                sessionStorage.setItem('workPlanData', JSON.stringify(data));
            } catch (error) {
                console.error('保存到sessionStorage失败:', error);
            }
        }

        // 从sessionStorage恢复数据
        function loadFromSessionStorage() {
            try {
                const savedData = sessionStorage.getItem('workPlanData');
                if (!savedData) return;
                
                const data = JSON.parse(savedData);
                
                // 1. 恢复项目基本信息
                const projectInfoTable = document.querySelector('h2:first-of-type + table');
                if (projectInfoTable && projectInfoTable.rows.length > 1) {
                    const infoRow = projectInfoTable.rows[1];
                    if (data.project_name) infoRow.cells[0].innerHTML = data.project_name;
                    if (data.project_period) infoRow.cells[1].innerHTML = data.project_period;
                    if (data.project_leader) infoRow.cells[2].innerHTML = data.project_leader;
                    if (data.project_priority) infoRow.cells[3].innerHTML = data.project_priority;
                    if (data.project_desc) infoRow.cells[4].innerHTML = data.project_desc;
                }
                
                // 2. 恢复页面开发任务
                if (data.pageTaskData) {
                    const pageTable = document.getElementById('pageTaskTable');
                    if (pageTable) {
                        // 清除现有数据行（保留表头和汇总行）
                        const summaryRow = pageTable.querySelector('.summary-row');
                        const existingRows = pageTable.querySelectorAll('tr:not(:first-child):not(.summary-row)');
                        existingRows.forEach(row => row.remove());
                        
                        // 重新创建行
                        data.pageTaskData.forEach(rowData => {
                            const newRow = document.createElement('tr');
                            rowData.forEach(cellData => {
                                const cell = document.createElement('td');
                                cell.innerHTML = cellData.content;
                                cell.className = cellData.className;
                                newRow.appendChild(cell);
                            });
                            
                            // 插入到汇总行之前
                            summaryRow.parentNode.insertBefore(newRow, summaryRow);
                            
                            // 为新行的可编辑单元格添加事件监听
                            const editableCells = newRow.querySelectorAll('.editable');
                            editableCells.forEach(cell => {
                                cell.addEventListener('dblclick', function() {
                                    if (!isEditing) {
                                        startEdit(this);
                                    }
                                });
                            });
                        });
                    }
                }
                
                // 3. 恢复技术实现任务
                if (data.techTaskData) {
                    const techTable = document.getElementById('techTaskTable');
                    if (techTable) {
                        // 清除现有数据行（保留表头和汇总行）
                        const summaryRow = techTable.querySelector('.summary-row');
                        const existingRows = techTable.querySelectorAll('tr:not(:first-child):not(.summary-row)');
                        existingRows.forEach(row => row.remove());
                        
                        // 重新创建行
                        data.techTaskData.forEach(rowData => {
                            const newRow = document.createElement('tr');
                            rowData.forEach(cellData => {
                                const cell = document.createElement('td');
                                cell.innerHTML = cellData.content;
                                cell.className = cellData.className;
                                newRow.appendChild(cell);
                            });
                            
                            // 插入到汇总行之前
                            summaryRow.parentNode.insertBefore(newRow, summaryRow);
                            
                            // 为新行的可编辑单元格添加事件监听
                            const editableCells = newRow.querySelectorAll('.editable');
                            editableCells.forEach(cell => {
                                cell.addEventListener('dblclick', function() {
                                    if (!isEditing) {
                                        startEdit(this);
                                    }
                                });
                            });
                        });
                    }
                }
                
                // 4. 恢复其他区域数据
                const otherEditableCells = document.querySelectorAll('.editable');
                otherEditableCells.forEach((cell, index) => {
                    try {
                        const table = cell.closest('table');
                        if (table && (table.id === 'pageTaskTable' || table.id === 'techTaskTable')) {
                            return; // 跳过任务表格
                        }
                        
                        let sectionName, rowIndex = 0, cellIndex = 0;
                        
                        // 检查是否是footer区域
                        const footerDiv = cell.closest('.footer');
                        if (footerDiv) {
                            // footer区域特殊处理
                            sectionName = 'footer';
                            const spans = footerDiv.querySelectorAll('.editable');
                            cellIndex = Array.from(spans).indexOf(cell);
                        } else if (table) {
                            // 表格内的单元格
                            const h2Element = table.previousElementSibling;
                            sectionName = h2Element?.textContent?.trim() || 'unknown';
                            const row = cell.closest('tr');
                            
                            if (table.rows && row) {
                                const rowsArray = Array.from(table.rows);
                                rowIndex = rowsArray.indexOf(row);
                                if (rowIndex === -1) rowIndex = 0;
                            }
                            
                            if (row && row.cells && cell) {
                                const cellsArray = Array.from(row.cells);
                                cellIndex = cellsArray.indexOf(cell);
                                if (cellIndex === -1) cellIndex = 0;
                            }
                        } else {
                            // 其他情况使用通用索引
                            sectionName = 'other';
                            cellIndex = index;
                        }
                        
                        const expectedKey = `${sectionName}_row${rowIndex}_cell${cellIndex}`;
                        
                        if (data[expectedKey]) {
                            // 特殊处理footer中的创建时间，如果已经有值就不覆盖
                            if (sectionName === 'footer' && cellIndex === 0) {
                                const currentContent = cell.innerHTML || '';
                                const importedContent = data[expectedKey].content || '';
                                
                                // 如果当前已有有效日期，且导入的是默认值，则保留当前值
                                if (currentContent && !currentContent.includes('[填写日期]') && 
                                    (importedContent.includes('[填写日期]') || importedContent.trim() === '')) {
                                    // 保留当前的创建时间，不覆盖
                                } else {
                                    cell.innerHTML = importedContent;
                                }
                            } else {
                                cell.innerHTML = data[expectedKey].content || '';
                            }
                            
                            if (data[expectedKey].className) {
                                cell.className = data[expectedKey].className;
                            }
                        }
                    } catch (error) {
                        console.warn('恢复单元格数据时出错:', error, cell);
                    }
                });
                
                // 恢复数据后，检查风险等级列并更新行样式
                const riskLevelCells = document.querySelectorAll('.risk-level-cell');
                riskLevelCells.forEach(cell => {
                    const row = cell.closest('tr');
                    const riskLevel = cell.textContent.trim();
                    if (row) {
                        // 移除所有风险样式类
                        row.classList.remove('risk-high', 'risk-medium', 'risk-low');
                        
                        // 根据风险等级添加对应样式类
                        switch(riskLevel) {
                            case '高':
                                row.classList.add('risk-high');
                                break;
                            case '中':
                                row.classList.add('risk-medium');
                                break;
                            case '低':
                                row.classList.add('risk-low');
                                break;
                        }
                    }
                });
                
                // 特殊恢复最后更新时间（非可编辑字段）
                const lastModifiedSpan = document.querySelector('.footer .datetime-display');
                if (lastModifiedSpan) {
                    if (data.last_modified_time && data.last_modified_time !== '[填写日期]' && data.last_modified_time !== '-' && data.last_modified_time.trim() !== '') {
                        lastModifiedSpan.textContent = data.last_modified_time;
                    } else {
                        // 如果没有保存的最后更新时间，保持为"-"
                        lastModifiedSpan.textContent = '-';
                    }
                }
                
                // 恢复数据后重新计算汇总
                updateOverallSummary();
            } catch (error) {
                console.error('从sessionStorage恢复数据失败:', error);
            }
        }

        function cancelEdit(originalText) {
            if (!isEditing || !currentEditCell) return;
            
            currentEditCell.innerHTML = originalText;
            currentEditCell.classList.remove('editing');
            
            isEditing = false;
            currentEditCell = null;
        }

        function updateStatusClass(cell, text) {
            // 移除所有状态类
            cell.classList.remove('status-pending', 'status-progress', 'status-completed', 'status-delayed', 'status-cancelled');
            
            // 根据文本内容添加对应状态类
            if (text.includes('未开始')) {
                cell.classList.add('status-pending');
            } else if (text.includes('进行中')) {
                cell.classList.add('status-progress');
            } else if (text.includes('已完成')) {
                cell.classList.add('status-completed');
            } else if (text.includes('已延期')) {
                cell.classList.add('status-delayed');
            } else if (text.includes('已取消')) {
                cell.classList.add('status-cancelled');
            }
        }

        function generateWordDocument() {
            generateWordDocumentFallback();
        }
        
        // 生成动态文件名
        function generateFileName(extension) {
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0');
            const day = String(now.getDate()).padStart(2, '0');
            const hour = String(now.getHours()).padStart(2, '0');
            const minute = String(now.getMinutes()).padStart(2, '0');
            const second = String(now.getSeconds()).padStart(2, '0');
            const timestamp = `${year}${month}${day}${hour}${minute}${second}`;
            
            // 获取负责人姓名
            let responsiblePerson = '';
            const projectInfoTable = document.querySelector('h2:first-of-type + table');
            if (projectInfoTable && projectInfoTable.rows.length > 1) {
                const responsibleCell = projectInfoTable.rows[1].cells[2]; // 负责人在第3列
                if (responsibleCell) {
                    responsiblePerson = responsibleCell.textContent.trim().replace(/\[|\]/g, '');
                    if (responsiblePerson === '您的姓名' || responsiblePerson === '填写') {
                        responsiblePerson = '';
                    }
                }
            }
            
            let fileName = `前端开发工作计划表_${timestamp}`;
            if (responsiblePerson) {
                fileName += `_${responsiblePerson}`;
            }
            fileName += `.${extension}`;
            return fileName;
        }

        // 生成Word兼容的DOC文件
        function generateWordDocumentFallback() {
            try {
                // 导出前更新最后更新时间（只在有缓存时更新页面）
                updateLastModified();
                // 获取清理后的内容
                const contentElement = document.querySelector('body');
                const clonedContent = contentElement.cloneNode(true);
                
                // 在导出的文档中更新最后更新时间
                const exportLastModifiedSpan = clonedContent.querySelector('.footer .datetime-display');
                if (exportLastModifiedSpan) {
                    // 在导出的文档中总是使用当前最新时间
                    exportLastModifiedSpan.textContent = getCurrentDateTimeString();
                }
                
                // 清理控制元素
                const controls = clonedContent.querySelector('.controls');
                if (controls) controls.remove();
                
                const buttons = clonedContent.querySelectorAll('button');
                buttons.forEach(btn => btn.remove());
                
                const scripts = clonedContent.querySelectorAll('script');
                scripts.forEach(script => script.remove());
                
                const btnContainers = clonedContent.querySelectorAll('.btn-container');
                btnContainers.forEach(container => container.remove());
                
                // 移除使用说明部分
                const usageNotes = clonedContent.querySelectorAll('.notes');
                usageNotes.forEach(note => {
                    if (note.textContent.includes('使用说明') || note.textContent.includes('双击任何蓝色背景的单元格即可进行编辑')) {
                        note.remove();
                    }
                });
                
                // 移除操作列
                const tables = clonedContent.querySelectorAll('table');
                tables.forEach(table => {
                    if (table.rows.length > 0) {
                        // 检查表头是否有"操作"列
                        let operationIndex = -1;
                        const headerRow = table.rows[0];
                        for (let i = 0; i < headerRow.cells.length; i++) {
                            if (headerRow.cells[i].textContent.trim() === '操作') {
                                operationIndex = i;
                                break;
                            }
                        }
                        
                        // 如果找到操作列，删除所有行的该列
                        if (operationIndex !== -1) {
                            for (let row of table.rows) {
                                if (row.cells[operationIndex]) {
                                    row.deleteCell(operationIndex);
                                }
                            }
                        }
                    }
                });
                
                // 创建Word兼容的HTML内容（A3横向设置）
                const htmlContent = `
                    <!DOCTYPE html>
                    <html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word">
                    <head>
                        <meta charset="UTF-8">
                        <title>前端开发工作计划表</title>
                        <!--[if gte mso 9]>
                        <xml>
                            <w:WordDocument>
                                <w:View>Print</w:View>
                                <w:Zoom>90</w:Zoom>
                                <w:DoNotPromptForConvert/>
                            </w:WordDocument>
                        </xml>
                        <![endif]-->
                        <!--[if gte mso 9]>
                        <xml>
                            <w:SectionProperties>
                                <w:PageSz w:w="23811" w:h="16838" w:orient="landscape" w:code="9"/>
                                <w:PageMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/>
                            </w:SectionProperties>
                        </xml>
                        <![endif]-->
                        <style>
                            
                            body { font-family: "Microsoft YaHei", Arial, sans-serif; margin: 20px; line-height: 1.5; }
                            h1 { text-align: center; color: #333; margin-bottom: 30px; font-size: 18pt; }
                            table { width: 100%; border-collapse: collapse; margin-bottom: 20px; font-size: 10pt; }
                            th, td { border: 1px solid #000; padding: 8px; text-align: left; vertical-align: top; }
                            th { background-color: #f5f5f5; font-weight: bold; text-align: center; }
                            .status-completed { background-color: #d4edda; color: #155724; }
                            .status-progress { background-color: #cce5ff; color: #004085; }
                            .status-in-progress { background-color: #cce5ff; color: #004085; }
                            .status-pending { background-color: #fff3cd; color: #856404; }
                            .status-delayed { background-color: #f8d7da; color: #721c24; }
                            .status-cancelled { background-color: #f1f3f4; color: #495057; }
                            .status-blocked { background-color: #f1f3f4; color: #495057; }
                            .summary-row { background-color: #e9ecef; font-weight: bold; }
                            .footer { margin-top: 30px; text-align: center; font-size: 9pt; color: #666; }
                        </style>
                    </head>
                    <body>
                        ${clonedContent.innerHTML}
                    </body>
                    </html>
                `;
                
                // 生成.doc文件（Word兼容格式）
                const blob = new Blob(['\ufeff', htmlContent], { 
                    type: 'application/msword;charset=utf-8' 
                });
                
                // 下载文件
                const fileName = generateFileName('doc');
                if (typeof saveAs !== 'undefined') {
                    saveAs(blob, fileName);
                } else {
                    const url = URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = fileName;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    URL.revokeObjectURL(url);
                }
                
                alert('Word文档已生成！\n文件格式：.doc（Word兼容格式）\n可直接在Word中打开。');
            } catch (error) {
                console.error('备用方案也失败了:', error);
                alert('抱歉，文档生成失败。请尝试手动复制内容到Word中。');
            }
        }
        
                // 生成HTML文档（恢复原有功能）
        function generateHTMLDocument() {
            try {
                // 导出前更新最后更新时间（只在有缓存时更新页面）
                updateLastModified();
                // 克隆当前文档，然后直接操作DOM移除控制面板
                const clonedDoc = document.cloneNode(true);
                
                // 在导出的文档中更新最后更新时间
                const exportLastModifiedSpan = clonedDoc.querySelector('.footer .datetime-display');
                if (exportLastModifiedSpan) {
                    // 在导出的文档中总是使用当前最新时间
                    exportLastModifiedSpan.textContent = getCurrentDateTimeString();
                }
            
            // 直接找到并移除控制面板
            const controlsDiv = clonedDoc.querySelector('.controls');
            if (controlsDiv) {
                controlsDiv.remove();
            }
            
            // 移除所有按钮
            const buttons = clonedDoc.querySelectorAll('button');
            buttons.forEach(btn => btn.remove());
            
            // 移除所有新增按钮容器
            const btnContainers = clonedDoc.querySelectorAll('.btn-container');
            btnContainers.forEach(container => container.remove());
            
            // 移除所有脚本
            const scripts = clonedDoc.querySelectorAll('script');
            scripts.forEach(script => script.remove());
            
            // 移除使用说明部分
            const usageNotes = clonedDoc.querySelectorAll('.notes');
            usageNotes.forEach(note => {
                if (note.textContent.includes('使用说明') || note.textContent.includes('双击任何蓝色背景的单元格即可进行编辑')) {
                    note.remove();
                }
            });
            
            // 移除操作列
            const tables = clonedDoc.querySelectorAll('table');
            tables.forEach(table => {
                if (table.rows.length > 0) {
                    // 检查表头是否有"操作"列
                    let operationIndex = -1;
                    const headerRow = table.rows[0];
                    for (let i = 0; i < headerRow.cells.length; i++) {
                        if (headerRow.cells[i].textContent.trim() === '操作') {
                            operationIndex = i;
                            break;
                        }
                    }
                    
                    // 如果找到操作列，删除所有行的该列
                    if (operationIndex !== -1) {
                        for (let row of table.rows) {
                            if (row.cells[operationIndex]) {
                                row.deleteCell(operationIndex);
                            }
                        }
                    }
                }
            });
            
            // 获取处理后的HTML
            let finalHtml = clonedDoc.documentElement.outerHTML;
            
            // 移除编辑相关的类
            finalHtml = finalHtml
                .replace(/class="[^"]*editable[^"]*"/g, function(match) {
                    return match
                        .replace(/\s*editable\s*/, ' ')
                        .replace(/\s*status-cell\s*/, ' ')
                        .replace(/\s*date-cell\s*/, ' ')
                        .replace(/\s*date-range-cell\s*/, ' ')
                        .replace(/\s*priority-cell\s*/, ' ');
                })
                .replace(/class="[^"]*editing[^"]*"/g, '')
                .replace(/class="[^"]*status-select[^"]*"/g, '')
                .replace(/\s+class=""/g, '')
                .replace(/前端开发工作计划表 - 可编辑版/g, '前端开发工作计划表');
            
            // 移除onclick等事件属性
            finalHtml = finalHtml.replace(/onclick="[^"]*"/g, '');
            finalHtml = finalHtml.replace(/onchange="[^"]*"/g, '');
            finalHtml = finalHtml.replace(/ondblclick="[^"]*"/g, '');
            
            // 移除控制面板相关的CSS样式
            finalHtml = finalHtml
                .replace(/\/\* 控制按钮样式 \*\/[\s\S]*?\/\* 其他样式 \*\//g, '')
                .replace(/\.controls[^}]*}/g, '')
                .replace(/\.btn[^}]*}/g, '')
                .replace(/\.btn:hover[^}]*}/g, '')
                .replace(/\.btn-success[^}]*}/g, '')
                .replace(/\.btn-success:hover[^}]*}/g, '')
                    .replace(/\.btn-primary[^}]*}/g, '')
                    .replace(/\.btn-primary:hover[^}]*}/g, '')
                .replace(/\.edit-hint[^}]*}/g, '')
                .replace(/\.status-select[^}]*}/g, '')
                .replace(/\.date-picker[^}]*}/g, '')
                .replace(/\.table-btn[^}]*}/g, '')
                .replace(/\.btn-container[^}]*}/g, '')
                .replace(/\.editable[^}]*}/g, '')
                .replace(/\.editing[^}]*}/g, '')
                .replace(/\.edit-input[^}]*}/g, '');
            
            // 最终验证
            const hasControls = finalHtml.includes('class="controls"');
            const hasButtons = finalHtml.includes('<button') || 
                                  finalHtml.includes('生成Word文档') || 
                                  finalHtml.includes('生成HTML文档') || 
                              finalHtml.includes('重置数据') || 
                              finalHtml.includes('打印文档');
            

            
            if (hasControls || hasButtons) {
                console.warn('警告：仍有残留，进行字符串清理...');
                // 备用字符串清理 - 按行过滤
                const lines = finalHtml.split('\n');
                const filteredLines = [];
                for (let i = 0; i < lines.length; i++) {
                    const line = lines[i];
                        if (!line.includes('生成Word文档') && 
                            !line.includes('生成HTML文档') && 
                        !line.includes('重置数据') && 
                        !line.includes('打印文档') &&
                        !line.includes('controls') &&
                        !line.includes('<button')) {
                        filteredLines.push(line);
                    }
                }
                finalHtml = filteredLines.join('\n');
            }
            
            // 创建下载链接
            const blob = new Blob([finalHtml], { type: 'text/html;charset=utf-8' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = generateFileName('html');
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            
                alert('HTML文档已生成！\n文件已清理所有编辑控件，可直接使用。');
                
            } catch (error) {
                console.error('生成HTML文档时出错:', error);
                alert('生成HTML文档失败，请检查控制台错误信息');
            }
        }

        // 新增页面任务行
        function addPageRow() {
            const table = document.getElementById('pageTaskTable');
            const summaryRow = table.querySelector('.summary-row');
            
            if (!table || !summaryRow) {
                alert('找不到页面任务表格或汇总行');
                return;
            }
            
            // 获取当前最大序号
            let maxNumber = 0;
            const rows = table.querySelectorAll('tr:not(.summary-row)');
            for (let i = 1; i < rows.length; i++) { // 跳过表头
                const firstCell = rows[i].cells[0];
                if (firstCell && !isNaN(firstCell.textContent)) {
                    maxNumber = Math.max(maxNumber, parseInt(firstCell.textContent));
                }
            }
            
            const newRow = document.createElement('tr');
            newRow.innerHTML = `
                <td>${maxNumber + 1}</td>
                <td class="editable">[页面名称]</td>
                <td class="editable">[功能描述]</td>
                <td class="editable">[开发内容]</td>
                <td class="editable">[X天]</td>
                <td class="editable date-cell">[日期]</td>
                <td class="editable date-cell">[日期]</td>
                <td class="editable status-cell status-pending">未开始</td>
                <td class="editable"></td>
            `;
            
            // 在汇总行之前插入新行
            summaryRow.parentNode.insertBefore(newRow, summaryRow);
            
            // 将最后一个单元格改为删除按钮
            let lastCell = newRow.querySelector('td:last-child');
            if (lastCell) {
                lastCell.innerHTML = '<button class="table-btn" onclick="deleteRow(this)">删除</button>';
            }
            
            // 为新行的可编辑单元格添加事件监听
            const editableCells = newRow.querySelectorAll('.editable');
            editableCells.forEach(cell => {
                cell.addEventListener('dblclick', function() {
                    if (!isEditing) {
                        startEdit(this);
                    }
                });
            });
            
            updateTableSummary('pageTaskTable');
            updateOverallSummary();
            saveToSessionStorage();
        }

        // 新增技术任务行
        function addTechRow() {
            const table = document.getElementById('techTaskTable');
            const summaryRow = table.querySelector('.summary-row');
            
            if (!table || !summaryRow) {
                alert('找不到技术任务表格或汇总行');
                return;
            }
            
            // 获取当前最大序号
            let maxNumber = 0;
            const rows = table.querySelectorAll('tr:not(.summary-row)');
            for (let i = 1; i < rows.length; i++) { // 跳过表头
                const firstCell = rows[i].cells[0];
                if (firstCell && !isNaN(firstCell.textContent)) {
                    maxNumber = Math.max(maxNumber, parseInt(firstCell.textContent));
                }
            }
            
            const newRow = document.createElement('tr');
            newRow.innerHTML = `
                <td>${maxNumber + 1}</td>
                <td class="editable">[技术任务]</td>
                <td class="editable">[具体内容]</td>
                <td class="editable">[X天]</td>
                <td class="editable date-cell">[日期]</td>
                <td class="editable date-cell">[日期]</td>
                <td class="editable status-cell status-pending">未开始</td>
                <td class="editable"></td>
            `;
            
            // 在汇总行之前插入新行
            summaryRow.parentNode.insertBefore(newRow, summaryRow);
            
            // 将最后一个单元格改为删除按钮
            let lastCell = newRow.querySelector('td:last-child');
            if (lastCell) {
                lastCell.innerHTML = '<button class="table-btn" onclick="deleteRow(this)">删除</button>';
            }
            
            // 为新行的可编辑单元格添加事件监听
            const editableCells = newRow.querySelectorAll('.editable');
            editableCells.forEach(cell => {
                cell.addEventListener('dblclick', function() {
                    if (!isEditing) {
                        startEdit(this);
                    }
                });
            });
            
            updateTableSummary('techTaskTable');
            updateOverallSummary();
            saveToSessionStorage();
        }

        // 删除任务行
        function deleteRow(btn) {
            if (!confirm('确定要删除此行吗？')) return;
            const row = btn.closest('tr');
            if (!row) return;
            const tbody = row.parentNode;
            row.remove();
            // 重新编号
            const rows = tbody.querySelectorAll('tr:not(.summary-row)');
            let number = 0;
            for (let i = 1; i < rows.length; i++) { // 跳过表头
                const firstCell = rows[i].cells[0];
                if (firstCell) {
                    number++;
                    firstCell.textContent = number;
                }
            }
            // 更新汇总
            const tableId = tbody.parentNode.id;
            updateTableSummary(tableId);
            updateOverallSummary();
            saveToSessionStorage();
        }

        // 清除sessionStorage缓存
        function clearSessionStorage() {
            try {
                sessionStorage.removeItem('workPlanData');
            } catch (error) {
                console.error('清除sessionStorage失败:', error);
            }
        }

        // 重置所有数据
        function resetAllData() {
            if (confirm('确定要重置所有数据吗？此操作不可撤销。')) {
                clearSessionStorage();
                
                // 重置最后更新时间为"-"
                const updateTimeSpan = document.querySelector('.footer .datetime-display');
                if (updateTimeSpan) {
                    updateTimeSpan.textContent = '-';
                }
                
                location.reload();
            }
        }

        // 打印文档
        function printDocument() {
            // 在打印前隐藏使用说明部分
            const usageNotes = [];
            const notesElements = document.querySelectorAll('.notes');
            
            notesElements.forEach(note => {
                const h3Elements = note.querySelectorAll('h3');
                let hasUsageContent = false;
                
                h3Elements.forEach(h3 => {
                    if (h3.textContent.includes('使用说明') || 
                        h3.textContent.includes('推荐工作流程') ||
                        h3.textContent.includes('双击任何蓝色背景的单元格即可进行编辑')) {
                        hasUsageContent = true;
                    }
                });
                
                if (hasUsageContent) {
                    usageNotes.push({
                        element: note,
                        originalDisplay: note.style.display
                    });
                    note.style.display = 'none';
                    note.classList.add('usage-notes');
                }
            });
            
            // 隐藏操作列（如果CSS不生效的话）
            const operationHeaders = [];
            const operationCells = [];
            
            // 找到所有表格的操作列
            const tables = document.querySelectorAll('table');
            tables.forEach(table => {
                if (table.rows.length > 0) {
                    // 检查表头是否有"操作"列
                    let operationIndex = -1;
                    const headerRow = table.rows[0];
                    for (let i = 0; i < headerRow.cells.length; i++) {
                        if (headerRow.cells[i].textContent.trim() === '操作') {
                            operationIndex = i;
                            break;
                        }
                    }
                    
                    // 如果找到操作列，隐藏所有行的该列
                    if (operationIndex !== -1) {
                        for (let row of table.rows) {
                            if (row.cells[operationIndex]) {
                                const cell = row.cells[operationIndex];
                                operationCells.push({
                                    element: cell,
                                    originalDisplay: cell.style.display
                                });
                                cell.style.display = 'none';
                            }
                        }
                    }
                }
            });
            
            // 执行打印
            window.print();
            
            // 打印完成后恢复隐藏的元素
            setTimeout(() => {
                // 恢复使用说明部分
                usageNotes.forEach(item => {
                    item.element.style.display = item.originalDisplay;
                    item.element.classList.remove('usage-notes');
                });
                
                // 恢复操作列
                operationCells.forEach(item => {
                    item.element.style.display = item.originalDisplay;
                });
            }, 1000); // 延迟1秒确保打印对话框已关闭
        }

        // 导出项目数据为JSON文件
        function exportProjectData() {
            try {
                // 导出前更新最后更新时间（只在有缓存时更新页面）
                updateLastModified();
                // 手动收集当前所有数据，确保是最新的
                const data = {};
                
                // 1. 项目基本信息
                const projectInfoTable = document.querySelector('h2:first-of-type + table');
                if (projectInfoTable && projectInfoTable.rows.length > 1) {
                    const infoRow = projectInfoTable.rows[1];
                    data['project_name'] = infoRow.cells[0]?.innerHTML || '';
                    data['project_period'] = infoRow.cells[1]?.innerHTML || '';
                    data['project_leader'] = infoRow.cells[2]?.innerHTML || '';
                    data['project_priority'] = infoRow.cells[3]?.innerHTML || '';
                    data['project_desc'] = infoRow.cells[4]?.innerHTML || '';
                }
                
                // 2. 页面开发任务
                const pageTable = document.getElementById('pageTaskTable');
                if (pageTable) {
                    const pageData = [];
                    for (let i = 1; i < pageTable.rows.length; i++) {
                        const row = pageTable.rows[i];
                        if (row.classList.contains('summary-row')) break;
                        
                        const rowData = [];
                        for (let j = 0; j < row.cells.length; j++) {
                            rowData.push({
                                content: row.cells[j].innerHTML,
                                className: row.cells[j].className
                            });
                        }
                        pageData.push(rowData);
                    }
                    data['pageTaskData'] = pageData;
                }
                
                // 3. 技术实现任务
                const techTable = document.getElementById('techTaskTable');
                if (techTable) {
                    const techData = [];
                    for (let i = 1; i < techTable.rows.length; i++) {
                        const row = techTable.rows[i];
                        if (row.classList.contains('summary-row')) break;
                        
                        const rowData = [];
                        for (let j = 0; j < row.cells.length; j++) {
                            rowData.push({
                                content: row.cells[j].innerHTML,
                                className: row.cells[j].className
                            });
                        }
                        techData.push(rowData);
                    }
                    data['techTaskData'] = techData;
                }
                
                // 4. 其他区域数据
                const otherEditableCells = document.querySelectorAll('.editable');
                otherEditableCells.forEach((cell, index) => {
                    try {
                        const table = cell.closest('table');
                        if (table && (table.id === 'pageTaskTable' || table.id === 'techTaskTable')) {
                            return; // 跳过任务表格
                        }
                        
                        let sectionName, rowIndex = 0, cellIndex = 0;
                        
                        const footerDiv = cell.closest('.footer');
                        if (footerDiv) {
                            sectionName = 'footer';
                            const spans = footerDiv.querySelectorAll('.editable');
                            cellIndex = Array.from(spans).indexOf(cell);
                        } else if (table) {
                            const h2Element = table.previousElementSibling;
                            sectionName = h2Element?.textContent?.trim() || 'unknown';
                            const row = cell.closest('tr');
                            
                            if (table.rows && row) {
                                const rowsArray = Array.from(table.rows);
                                rowIndex = rowsArray.indexOf(row);
                                if (rowIndex === -1) rowIndex = 0;
                            }
                            
                            if (row && row.cells && cell) {
                                const cellsArray = Array.from(row.cells);
                                cellIndex = cellsArray.indexOf(cell);
                                if (cellIndex === -1) cellIndex = 0;
                            }
                        } else {
                            sectionName = 'other';
                            cellIndex = index;
                        }
                        
                        const key = `${sectionName}_row${rowIndex}_cell${cellIndex}`;
                        data[key] = {
                            content: cell.innerHTML || '',
                            className: cell.className || ''
                        };
                    } catch (error) {
                        console.warn('导出单元格数据时出错:', error, cell);
                    }
                });
                
                // 特殊保存最后更新时间（非可编辑字段）
                const lastModifiedSpan = document.querySelector('.footer .datetime-display');
                if (lastModifiedSpan) {
                    // 在导出的备份数据中总是使用当前最新时间
                    data['last_modified_time'] = getCurrentDateTimeString();
                }
                
                // 添加导出时间和版本信息
                data['_metadata'] = {
                    exportTime: new Date().toISOString(),
                    version: '1.0',
                    description: '前端开发工作计划表数据文件'
                };
                
                // 生成文件名
                const fileName = generateDataFileName();
                
                // 创建并下载JSON文件
                const jsonString = JSON.stringify(data, null, 2);
                const blob = new Blob([jsonString], { type: 'application/json;charset=utf-8' });
                
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = fileName;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
                
                alert(`项目数据已导出！\n文件名：${fileName}\n可用于下次导入恢复所有编辑内容。`);
                
            } catch (error) {
                console.error('导出项目数据失败:', error);
                alert('导出项目数据失败，请检查控制台错误信息。');
            }
        }

        // 生成数据文件名
        function generateDataFileName() {
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0');
            const day = String(now.getDate()).padStart(2, '0');
            const hour = String(now.getHours()).padStart(2, '0');
            const minute = String(now.getMinutes()).padStart(2, '0');
            const second = String(now.getSeconds()).padStart(2, '0');
            const timestamp = `${year}${month}${day}_${hour}${minute}${second}`;
            
            // 获取项目名称
            let projectName = '前端开发工作计划表';
            const projectInfoTable = document.querySelector('h2:first-of-type + table');
            if (projectInfoTable && projectInfoTable.rows.length > 1) {
                const projectCell = projectInfoTable.rows[1].cells[0];
                if (projectCell) {
                    const name = projectCell.textContent.trim().replace(/\[|\]/g, '');
                    if (name && name !== '填写项目名称') {
                        projectName = name;
                    }
                }
            }
            
            return `${projectName}_数据备份_${timestamp}.json`;
        }

        // 导入项目数据
        function importProjectData() {
            const fileInput = document.getElementById('importFileInput');
            if (fileInput) {
                fileInput.click();
            }
        }

        // 处理文件导入
        function handleFileImport(event) {
            const file = event.target.files[0];
            if (!file) return;
            
            if (!file.name.toLowerCase().endsWith('.json')) {
                alert('请选择JSON格式的数据文件！');
                return;
            }
            
            const reader = new FileReader();
            reader.onload = function(e) {
                try {
                    const jsonData = JSON.parse(e.target.result);
                    
                    // 验证数据格式
                    if (!jsonData || typeof jsonData !== 'object') {
                        alert('无效的数据文件格式！');
                        return;
                    }
                    
                    // 确认导入
                    const confirmMessage = `确定要导入数据吗？\n这将覆盖当前所有编辑内容！\n\n文件信息：\n` +
                        (jsonData._metadata ? 
                            `导出时间：${new Date(jsonData._metadata.exportTime).toLocaleString()}\n` +
                            `版本：${jsonData._metadata.version}\n` +
                            `说明：${jsonData._metadata.description}` 
                            : '未知数据文件');
                    
                    if (!confirm(confirmMessage)) {
                        return;
                    }
                    
                    // 导入数据
                    importProjectDataFromJson(jsonData);
                    
                    alert('数据导入成功！页面将自动刷新以完成加载。');
                    
                    // 清空文件输入框，允许重复选择同一文件
                    event.target.value = '';
                    
                } catch (error) {
                    console.error('解析JSON文件失败:', error);
                    alert('数据文件格式错误，无法解析！\n请确保选择的是正确的项目数据文件。');
                }
            };
            
            reader.readAsText(file, 'UTF-8');
        }

        // 从JSON数据导入到页面
        function importProjectDataFromJson(data) {
            try {
                // 先保存到sessionStorage，然后刷新页面
                sessionStorage.setItem('workPlanData', JSON.stringify(data));
                
                // 延迟刷新，确保数据保存完成
                setTimeout(() => {
                    location.reload();
                }, 100);
                
            } catch (error) {
                console.error('导入数据失败:', error);
                alert('导入数据失败：' + error.message);
            }
        }

        // 初始化底部时间字段
        function initializeFooterTimes() {
            // 初始化创建时间
            const createTimeSpan = document.querySelector('.footer .editable.date-cell');
            if (createTimeSpan && (createTimeSpan.textContent.includes('[填写日期]') || createTimeSpan.textContent.trim() === '')) {
                createTimeSpan.textContent = getCurrentDateString();
            }
            
            // 初始化最后更新时间 - 首次进入时保持为"-"
            const updateTimeSpan = document.querySelector('.footer .datetime-display');
            if (updateTimeSpan && updateTimeSpan.textContent.trim() === '') {
                updateTimeSpan.textContent = '-';
            }
        }

        // 更新最后更新时间（在导出时调用）
        function updateLastModified() {
            const updateTimeSpan = document.querySelector('.footer .datetime-display');
            
            // 检查是否有缓存数据
            const savedData = sessionStorage.getItem('workPlanData');
            const hasCache = savedData && JSON.parse(savedData);
            
            // 只有在有缓存数据时才更新页面显示
            if (updateTimeSpan && hasCache) {
                updateTimeSpan.textContent = getCurrentDateTimeString();
                
                // 同时更新sessionStorage中的最后更新时间
                try {
                    const data = JSON.parse(savedData);
                    data['last_modified_time'] = getCurrentDateTimeString();
                    sessionStorage.setItem('workPlanData', JSON.stringify(data));
                } catch (error) {
                    console.warn('更新sessionStorage中的最后更新时间失败:', error);
                }
            }
        }
        
        // 获取当前时间用于导出（不更新页面显示）
        function getCurrentTimeForExport() {
            return getCurrentDateTimeString();
        }
    </script>
</body>
</html>

